/*
* Demo for Nacos
* pom.xml
    <dependency>
        <groupId>com.alibaba.nacos</groupId>
        <artifactId>nacos-client</artifactId>
        <version>${version}</version>
    </dependency>
*/
package com.zm.demo.nacos;

import java.io.FileReader;
import java.io.IOException;
import java.util.Objects;
import java.util.Properties;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicInteger;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;

/**
 * Config service example
 * 
 * @author Nacos
 *
 */
public class ConfigExample {

	public static void main(String[] args) throws NacosException, InterruptedException, IOException {
		String serverAddr = "172.18.40.101:8848";
		String dataId = "store.mode";
		String group = "SEATA_GROUP";
		Properties properties = new Properties();
		properties.put(PropertyKeyConst.SERVER_ADDR, serverAddr);
//		properties.put("namespace", "seata");
		properties.put("namespace", "438049c6-92cf-4991-bad5-bebadb59b21a");
		ConfigService configService = NacosFactory.createConfigService(properties);

		Properties config = new Properties();
		config.load(new FileReader("C:\\code\\demo\\demo-nacos\\src\\main\\resources\\config.txt"));
		AtomicInteger count = new AtomicInteger(0);
		config.entrySet().stream().forEach(e ->{
			//String dataId, String group, String content
			try {
				configService.publishConfig(Objects.toString(e.getKey()), "SEATA_GROUP", Objects.toString(e.getValue()));
				System.out.println(count.incrementAndGet());
			} catch (NacosException ex) {
				ex.printStackTrace();
			}
		});
		String content = configService.getConfig(dataId, group, 5000);
		System.out.println(content);
		configService.addListener(dataId, group, new Listener() {
			@Override
			public void receiveConfigInfo(String configInfo) {
				System.out.println("recieve:" + configInfo);
			}

			@Override
			public Executor getExecutor() {
				return null;
			}
		});
		
		boolean isPublishOk = configService.publishConfig(dataId, group, "content");
		System.out.println(isPublishOk);
		
		Thread.sleep(3000);
		content = configService.getConfig(dataId, group, 5000);
		System.out.println(content);

		boolean isRemoveOk = configService.removeConfig(dataId, group);
		System.out.println(isRemoveOk);
		Thread.sleep(3000);

		content = configService.getConfig(dataId, group, 5000);
		System.out.println(content);
		Thread.sleep(300000);

	}
}
